package com.ip.student.service;

import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.ip.student.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ip.student.mapper.StudentPhysicalMapper;
import com.ip.student.models.service.IStudentPhysicalService;
import com.ip.student.models.bo.StudentPhysicalSaveBO;
import com.ip.student.models.dto.StudentPhysicalDTO;
import java.util.Date;
import java.util.List;

/**
 * 体测信息控制器
 *
 * @author 张景奇
 * @Date 2025-11-04 14:08:58
 */
@DubboService
public class StudentPhysicalServiceImpl extends ServiceImpl<StudentPhysicalMapper, StudentPhysicalDTO> implements IStudentPhysicalService{

    private static final Logger log = LoggerFactory.getLogger(StudentPhysicalServiceImpl.class);

    @Resource
    private YmlConfig ymlConfig;
    
    @Resource
    private StudentPhysicalMapper studentPhysicalMapper;

    @Override
    public boolean add(StudentPhysicalSaveBO saveBO) {
        log.info("服务层接收到的体测信息: {}", saveBO);
        StudentPhysicalDTO dto = new StudentPhysicalDTO();
        BeanUtils.copyProperties(saveBO,dto);
        log.info("复制属性后的DTO: {}", dto);
        
        // 如果前端传回的ID为null或0，则使用雪花算法生成ID
        if (saveBO.getPhysicalId() == null || saveBO.getPhysicalId() == 0) {
            Long id = ymlConfig.getPkId();
            // 确保生成的ID为正数且在Integer范围内
            if (id < 0) {
                id = Math.abs(id);
            }
            // 确保ID在Integer范围内
            if (id > Integer.MAX_VALUE) {
                id = id % Integer.MAX_VALUE;
            }
            // 确保ID不为0
            if (id == 0) {
                id = 1L;
            }
            // 只设置physicalId字段，因为这是数据库的主键
            dto.setPhysicalId(id.intValue());
        } 
        // 如果physicalId已经存在且不为0，则直接使用传入的值
        
        // 如果前端没有传回创建时间，则使用当前时间
        if (saveBO.getCreateTime() == null) {
            dto.setCreateTime(new Date());
        }
        
        log.info("处理后的DTO: {}", dto);
        return this.insert(dto);
    }
    
    /**
     * 根据条件查询体测信息列表
     * @param studentPhysicalDTO 查询条件
     * @return 体测信息列表
     */
    public List<StudentPhysicalDTO> queryListByCondition(StudentPhysicalDTO studentPhysicalDTO) {
        return studentPhysicalMapper.queryListByCondition(studentPhysicalDTO);
    }
}